package com.iakuil.poc.domain;

import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import java.util.Collection;
import java.util.Date;
import java.util.Set;

@Data
@Entity
@Table(name = "sys_user")
public class User implements UserDetails {

    @Id
    private Long id;
    private String username;
    private String password;
    private String phone;
    private String email;
    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "sys_user_role", joinColumns = {@JoinColumn(name = "user_id")},
            inverseJoinColumns = {@JoinColumn(name = "role_id")})
    private Set<Role> roles;
    @Column(name = "create_time")
    private Date createTime;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        String[] roles = this.roles.stream().map(item -> "ROLE_" + item.getName()).distinct().toArray(String[]::new);
        return AuthorityUtils.createAuthorityList(roles);
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}